import React from 'react';
import Button from "../../../../node_modules/react-bootstrap/lib/Button";
import ListGroup from "react-bootstrap/lib/ListGroup";
import ListGroupItem from "react-bootstrap/lib/ListGroupItem";
import LeftNav from '../../../../node_modules/material-ui/lib/left-nav';
import Path from '../../lib/path.js';
import Modal from "../../../../node_modules/react-bootstrap/lib/Modal";
import DropdownButton from 'react-bootstrap/lib/DropdownButton';
import MenuItem from 'react-bootstrap/lib/MenuItem';
import List from "../component/List.jsx";
import Form from '../../src/component/formElement/Form.jsx';
import Label from '../../src/component/formElement/Label.jsx'
import Input from '../../src/component/formElement/Input.jsx'
import Selector from '../../src/component/formElement/Selector.jsx'
import SelectList from '../../src/component/formElement/SelectList.jsx'

import HttpRequest from './../HttpRequest.js';


var ConfigManagementTab = React.createClass({
    getInitialState: function () {
        return ({
            current_project: this.props.current_project, //当前项目
            ListData: [], //配置数据
            ListItems: [], //左侧配置列表
            projects: [], //当前选中配置中包含的工程
            current_selected: null //当前选中配置
        });
    },

    componentWillReceiveProps: function (newProps) {
        this.setState({
            current_project: newProps.current_project
        }, function () {
            this.componentWillMount();
        });
    },
    componentWillMount: function () {
        HttpRequest.getAllProductConfigs(this.state.current_project._id).success(function (configs) {
            //ob._renderList(configs.data)
            if (configs.code == 0) {
                this.setState({
                    ListData: configs.data
                }, this._renderList)
            } else {
                toastr.error(null, "获取产品配置失败！");
            }
        }.bind(this)).error(function (err) {
            toastr.error(null, "获取产品配置失败！");
        });
    },
    itemSelected: function (config) {
        projects = [];
        HttpRequest.getProductConfigById(config._id).success(function (res) {
            if (res.code != 0) {
                toastr.error(null, res.message);
            } else {
                this.setState({
                    current_selected: res.data,
                    projects: res.data.projects
                });
            }
        }.bind(this)).error(function (err) {

        });

    },
    _renderList: function () {
        this.setState({
            List: <List ListData={this.state.ListData}
                        SelectedItemStyle={{background:"#f3f3f3"}}
                        onItemSelected={this.itemSelected}
                        itemDeleted={this.removeProductConfig}
                        ifEmpty={<span style={{color:"#969696",paddingLeft:"50px",fontSize:"14px",fontFamily:'Microsoft YaHei'}}>该项目没有产品配置！ </span>}
                        IconMap={[
                            {type:"mk_back",icon:<img src="/res/image/MK_h.png" />},
                            {type:"app_android",icon:<img src="/res/image/iphone_h.png"/>},
                            {type:"app_ios",icon:<img src="/res/image/iphone_h.png" />},
                            {type:"app_plugin",icon:<i className="fa fa-plug" style={{fontSize:"23px"}} aria-hidden="true"/>}
                        ]}
            />
        });
        if (this.state.ListData.length > 0) {
            this.setState({
                current_selected: this.state.ListData[this.state.ListData.length - 1]
            })
        } else {
            this.setState({
                current_selected: null
            })
        }
    },
    addConfig: function (event, eventKey) {
        var mk_count = 0;
        if (mk_count == 0) {
            mk_count = "";
        }
        this.state.ListData.map(function (item) {
            if (item.name == 'new_mk_cfg' + mk_count) {
                mk_count++;
            }
        });
        var mk_name = 'new_mk_cfg' + mk_count;
        var newMkConfig = {
            "name": mk_name,
            "project": this.state.current_project._id,
            "type": "mk_back",
            "version": "1",
            "detail": {
                "dependencies": {
                    "list": [],
                    "include-packaging": "true"
                }
            },
            "workspace": null,
            "projects": []
        };

        var android_count = 0;
        if (android_count == 0) {
            android_count = "";
        }
        this.state.ListData.map(function (item) {
            if (item.name == 'new_App_Android_cfg' + android_count) {
                android_count++;
            }
        });
        var android_name = 'new_App_Android_cfg' + android_count;
        var newAppAndroidConfig = {
            "name": android_name,
            "project": this.state.current_project._id,
            "type": "app_android",
            "version": "v1.0",
            "workspace": null,
            "detail": {
                "certificate": "default"
            },
            "projects": []
        };

        var ios_count = 0;
        if (ios_count == 0) {
            ios_count = "";
        }
        this.state.ListData.map(function (item) {
            if (item.name == 'new_App_ios_cfg' + ios_count) {
                ios_count++;
            }
        });
        var ios_name = 'new_App_ios_cfg' + ios_count;
        var newAppIosConfig = {
            "name": ios_name,
            "project": this.state.current_project._id,
            "type": "app_ios",
            "version": "v1.0",
            "detail": {
                "certificate": "default"
            },
            "workspace": null,
            "projects": []
        };

        var app_plugin_count = 0;
        if (app_plugin_count == 0) {
            app_plugin_count = "";
        }
        this.state.ListData.map(function (item) {
            if (item.name == 'new_App_Plugin_cfg' + app_plugin_count) {
                app_plugin_count++;
            }
        });
        var App_Plugin_name = 'new_App_Plugin_cfg' + app_plugin_count;
        var newAppPluginConfig = {
            "name": App_Plugin_name,
            "project": this.state.current_project._id,
            "type": "app_plugin",
            "version": "v1.0",
            "detail": {
                "resource_publication":false
            },
            "projects": []
        };

        var newConfig;
        switch (eventKey) {
            case "mk_back":
                newConfig = newMkConfig;
                break;
            case "app_android":
                newConfig = newAppAndroidConfig;
                break;
            case "app_ios":
                newConfig = newAppIosConfig;
                break;
            case "app_plugin":
                newConfig = newAppPluginConfig
        }
        HttpRequest.addProductConfig(newConfig).success(function (resp) {
            if (resp.code == 500) {
                toastr.error(null, "添加配置失败！");
            } else {
                this.componentWillMount();

            }
        }.bind(this)).error(function (error) {
            toastr.error(null, "添加配置失败！");
        });

    },
    removeProductConfig: function (config_id) {
        confirm("确定删除？", function () {
            HttpRequest.deleteProductConfig(config_id).success(function (resp) {
                if (resp.code != 500) {
                    this.componentWillMount();
                } else {
                    toastr.error(null, "删除失败");
                }
            }.bind(this)).error(function () {
                toastr.error(null, "删除失败");
            });
        }.bind(this));
    },
    saveEdit: function (cfg_id, postData) {
        HttpRequest.updateProductConfig(cfg_id, postData).success(function (res) {
            if (res.code == 0) {
                this.componentWillMount();
                toastr.success(null, "产品配置修改成功");
            } else {
                toastr.error(null, "产品配置修改失败");
            }
        }.bind(this)).error(function (msg) {
            toastr.error(null, "产品配置修改失败");
        });
    },
    render: function () {
        var content_pageRight = null;
        if (this.state.current_selected) {
            content_pageRight = <ProductConfigDetail
                saveEdit={this.saveEdit}
                current_selected={this.state.current_selected}
                current_project={this.state.current_project}
            />
        } else {
            content_pageRight = <div style={{textAlign:"center"}}>
                <div style={{color:"#969696",marginTop:"50px",fontSize:"14px",fontFamily:'Microsoft YaHei'}}>
                    <i className="fa fa-exclamation-circle"
                       style={{fontSize:"48px",cursor:"pointer"}}/>
                    <br/>
                    该项目没有产品配置！
                </div>
            </div>
        }
        return (
            <div style={{height:"100%"}}>

                <div className="content_pageLeft">
                    <span className="info_title" style={{paddingLeft:"30px"}}>产品配置</span>
                    <DropdownButton bsStyle="primary"
                                    onSelect={this.addConfig}
                                    style={{backgroundColor:"#555",height: "25px",paddingTop: "2px"}}
                                    title="新建" id="new_product_config">
                        <MenuItem eventKey="mk_back">mk产品</MenuItem>
                        <MenuItem eventKey="app_android">Android产品</MenuItem>
                        <MenuItem eventKey="app_ios">IOS产品</MenuItem>
                        <MenuItem eventKey="app_plugin">移动插件</MenuItem>
                    </DropdownButton>
                    <div style={{overflowY:"auto",height:"100%",maxHeight:"90%",marginTop:"5px"}}>
                        {this.state.List}
                    </div>

                </div>
                <div className="content_pageRight">
                    <span className="info_title">配置详情</span>
                    <div style={{width:"100%",height:"calc(100% - 63px)",marginTop: "20px"}}>
                        {content_pageRight}
                    </div>
                </div>

            </div>
        );
    }

});
export default ConfigManagementTab;

var projects_options = [];
var ProjectsList = React.createClass({
    getInitialState: function () {
        return ({
            current_selected: this.props.current_selected,
            projects: [],
            projectItem: [],
            current_project: this.props.current_project
        });
    },

    componentWillReceiveProps: function (newProps) {
        this.setState({
            current_selected: newProps.current_selected,
            current_project: newProps.current_project
        });
    },

    _getProjects: function () {
        var ob = this;
        if (ob.state.current_wkp != "没有工作空间") {
            window.loading();
            HttpRequest.getProjectsInMasterRepo(ob.state.current_project._id).success(function (res) {
                if (res.code != 500) {
                    var projects = [];
                    res.data.projects.map(function (item) {
                        for (var it in this.state.current_selected.projects) {
                            if (this.state.current_selected.projects[it].name ==  item.name) {
                                item['checked'] = true;
                                break;
                            } else {
                                item['checked'] = false;
                            }
                        }
                        var  i = 0;
                        if (this.state.current_selected.type == "mk_back") {
                            for (i = 0; i < item.natureIds.length; i++) {
                                if (item.natureIds[i] == "com.beecode.enzyme.mdt.core.ModelNature") {
                                    projects.push(item)
                                }
                            }
                        }else if(this.state.current_selected.type == "app_plugin"){
                            for (i = 0; i < item.natureIds.length; i++) {
                                if (item.natureIds[i] == "com.beecode.nectar.AppPluginNature") {
                                    projects.push(item)
                                }
                            }
                        } else {
                            for (i = 0; i < item.natureIds.length; i++) {
                                if (item.natureIds[i] == "com.beecode.nectar.AppNature") {
                                    projects.push(item)
                                }
                            }
                        }
                    }.bind(this));
                    projects_options = projects;
                    ob.setState({
                        projects: projects
                    }, function () {
                        ob._renderItems();
                        toastr.success(null, "获取工程成功!");
                    });

                }else{
                    toastr.error(null,"获取工程失败", {timeOut: 0});
                }
                window.removeLoading();
            }.bind(this));
        } else {
            ob.setState({
                projects: []
            }, function () {
                ob._renderItems()
            });
        }
    },

    handleClose: function () {
        this.setState({open: false});
    },
    handleOpen: function () {
        this.setState({open: true}, this._getProjects);
    },
    itemSelected: function (item) {
        //判断类型 如果是移动 只能选择一个
        var current_selected_config_info = this.state.current_selected;
        var checked_items = 0;
        this.state.projects.map(function(project){
            if (project.checked) {
                checked_items ++;
            }
        });
        if ((current_selected_config_info.type == "app_ios"
            || current_selected_config_info.type == "app_android")
            && checked_items) {
            toastr.error(null, "移动产品只能包含一个工程！");
            return false;
        }else if((current_selected_config_info.type == "app_plugin")
            && checked_items){
            toastr.error(null, "移动插件只能包含一个插件工程！");
            return false;
        }
        item["checked"] = !item["checked"];
        this._renderItems();
        document.getElementById("dis_select_all").src = "/res/image/check.png";
        document.getElementById("select_all").src = "/res/image/check.png";
    },
    handleComplete: function () {
        var selected = [];
        this.state.projects.map(function (item) {
            if (item.checked) {
                selected.push(item);
            }
        });
        this.props.getSelected(selected);
        this.handleClose();
    },
    _renderItems: function () {
        var items = [];
        var checkbox;
        this.state.projects.map(function (item, index) {
            checkbox = <img src="/res/image/check.png"/>;
            if (item.checked) {
                checkbox = <img src="/res/image/check_h.png"/>;
            }
            items.push(
                <div className="selector_item" id={"selection_"+index}
                     onClick={this.itemSelected.bind(this,item,index)}>
                                <span style={{width:"20px",height:"20px",display:"inline-block"}}>
                                     { checkbox}
                                </span>
                    <span style={{marginLeft:"10px"}}>{item.name}</span>
                </div>
            )
        }.bind(this));
        this.setState({
            projectItem: items
        });
    },
    search: function () {
        var input = document.getElementById("pdctcfg_search_input").value;
        var projects = projects_options;
        var projectsFiltered = [];
        if (input.length > 0) {
            for (var i = 0; i < projects.length; i++) {
                if (projects[i].name.indexOf(input) >= 0) {
                    projectsFiltered.push(projects[i]);
                }

            }
        } else {
            projectsFiltered = projects;
        }
        this.setState({
            projects: projectsFiltered
        }, this._renderItems);
    },
    disSelectAll: function () {
        var chec = document.getElementById("dis_select_all").src;
        if (chec == "/res/image/check_h.png") {
            document.getElementById("dis_select_all").src = "/res/image/check.png";
        } else {
            document.getElementById("select_all").src = "/res/image/check.png";
            document.getElementById("dis_select_all").src = "/res/image/check_h.png";
        }

        var projects = this.state.projects;
        projects.map(function (item) {
            item.checked = false;
        });
        this.setState({
            projects: projects
        }, this._renderItems);
    },
    selectAll: function () {
        var current_selected_config_info = this.state.current_selected;
        if ((current_selected_config_info.type == "app_ios"
            || current_selected_config_info.type == "app_android")
            && this.state.projects.length > 1) {
            toastr.error(null, "移动产品只能包含一个工程！");
            return false;
        }
        var chec = document.getElementById("select_all").src;
        if (chec == "/res/image/check_h.png") {
            document.getElementById("select_all").src = "/res/image/check.png";
        } else {
            document.getElementById("dis_select_all").src = "/res/image/check.png";
            document.getElementById("select_all").src = "/res/image/check_h.png";
        }
        var projects = this.state.projects;
        projects.map(function (item) {
            item.checked = true;
        });
        this.setState({
            projects: projects
        }, this._renderItems);
    },

    render: function () {
        return (
            <div>
                <Modal
                    show={this.state.open}
                    style={{borderRadius:"0"}}
                >
                    <Modal.Header style={{background:"#383F45"}}>
                        <Modal.Title style={{color:"white"}}>
                            <img src="/res/image/select.png" style={{float:"left"}}/>
                            <span style={{marginLeft: "10px",letterSpacing:"2px"}}>选择</span>
                            <img src="/res/image/close.png" style={{float:"right",cursor:"pointer",marginTop:" 5.5px"}}
                                 onClick={this.handleClose}/>
                        </Modal.Title>
                    </Modal.Header>
                    <Modal.Body>
                        <div>
                            <div
                                style={{width:"460px",height:"35px",border:"solid 1px lightgray",marginBottom:"18px"}}>
                                <input type="text" placeholder="输入您要搜索的内容" id="pdctcfg_search_input"
                                       onChange={this.search}
                                       style={{width: "420px",height:"30px",border: "none",float: "left",outline: "none",paddingLeft:"20px"}}/>
                            <span className="glyphicon glyphicon-search"
                                  style={{float:"right",height:"20px",width: "20px",marginTop: "6px",marginRight: "10px",fontSize:"20px",marginBottom: "auto"}}
                                  aria-hidden="true"/>
                            </div>
                            <div className="selector_dialog_body">
                                {(this.state.projectItem.length) ? this.state.projectItem :
                                    <span
                                        style={{color:"#969696",paddingLeft:"50px",fontSize:"14px",fontFamily:'Microsoft YaHei'}}>
                                        该项目没有创建工程！
                                    </span>
                                }
                            </div>
                            <div style={{ fontFamily:'Microsoft YaHei',fontSize:"15px",marginTop:"10px"}}>
                                <span onClick={this.selectAll} style={{cursor:"pointer"}}>
                                    <span style={{width:"20px",height:"20px",display:"inline-block"}}
                                          >
                                        <img id="select_all" src="/res/image/check.png"/>
                                    </span>
                                    <span style={{marginLeft:"10px"}}>全选</span>
                                </span>
                                <span onClick={this.disSelectAll} style={{cursor:"pointer"}}>
                                    <span style={{width:"20px",height:"20px",display:"inline-block",marginLeft:"20px"}}
                                          >
                                        <img id="dis_select_all" src="/res/image/check.png"/>
                                    </span>
                                    <span style={{marginLeft:"10px"}}>全不选</span>
                                </span>
                            </div>
                        </div>

                    </Modal.Body>
                    <Modal.Footer style={{borderTop:"none"}}>
                        <Button
                            onClick={this.handleComplete}
                            style={{backgroundColor: "#383F45", borderColor: "#383F45",width:"70px"}}
                            bsStyle="primary">完成</Button>
                    </Modal.Footer>
                </Modal>
            </div>
        )
    }

});

var ProductConfigDetail = React.createClass({
    getInitialState: function () {
        return ({
            current_selected: this.props.current_selected,
            current_project: this.props.current_project,
        });
    },

    componentWillReceiveProps: function (newProps) {
        this.setState({
            current_selected: newProps.current_selected,
            current_project: newProps.current_project
        });
    },
    update: function (cfg_id, postData) {
        this.props.saveEdit(cfg_id, postData);
    },
    render: function () {

        return (
            <div style={{height:"100%"}}>
                <Edit_config
                    update={this.update}
                    current_selected={this.state.current_selected}
                    current_project={this.state.current_project}/>
            </div>
        )
    },
});


var projects = [];
var Edit_config = React.createClass({
    getInitialState: function () {
        return ({
            current_selected: this.props.current_selected,
            current_project: this.props.current_project,
            projects: [],
            form_data: this.props.current_selected,
            certList: []
        });
    },

    componentWillReceiveProps: function (newProps) {
        this.setState({
            current_selected: newProps.current_selected,
            current_project: newProps.current_project,
            form_data: newProps.current_selected
        }, function () {
            this.componentWillMount();
        });
    },

    componentWillMount: function () {
        var ob = this;
        if (this.state.current_selected) {
            this.setState({
                projects: this.state.current_selected.projects
            });
        }
        var certsOfProject = this.state.current_project.certs;
        var certs = [{"key": "default", "value": "使用默认证书"}];
        certsOfProject.map(function (cert, index) {
            HttpRequest.getCert(cert).success(function (res) {
                if ((res.data.type == "Android" && ob.state.current_selected.type == "app_android")
                    || (res.data.type == "IOS" && ob.state.current_selected.type == "app_ios")) {
                    certs.push({
                        "key": res.data._id,
                        "value": res.data.name
                    });
                }

            }).error();
        });
        ob.setState({
            certList: certs
        });
    },
    editProjects: function (projectsSelected) {
        var pro = [];
        var current_selected = this.state.current_selected;
        projectsSelected.map(function (item) {
            var projectAdded = {
                "name": Path.basename(item.name),
                "location": item.location
            };
            pro.push(projectAdded);
        }.bind(this));
        current_selected.projects = pro;
        this.setState({
            current_selected: current_selected,
            projects: pro
        });
    },
    saveEdit: function () {
        var ob = this;
        var cfg_id = ob.state.current_selected._id;
        var detail = {};
        if (this.state.current_selected.type == "mk_back") {
            detail = {
                "dependencies": {
                    "include-packaging": ob.refs['include-packaging'].getValue(),
                    //"list": ob.refs['detail_list'].getValue()
                    "list": []
                }
            };
        } else if(this.state.current_selected.type == "app_plugin"){
            detail = {
                "resource_publication":ob.refs['resource_publication'].getValue()
            };
        }else {
            detail = {
                "certificate": ob.refs['certificate'].getValue()
            };
        }
        var postData = {
            "projects": ob.state.projects,
            //"projects":project_selected,
            "detail": detail,
            "version": ob.refs['version'].getValue(),
            "name": ob.refs['name'].getValue(),
            //"workspace": (ob.state.selected_wkp.key != "noWorkspace") ? ob.state.selected_wkp.key : null
        };
        this.props.update(cfg_id, postData);

    },
    formChanged: function (formEle_name) {
        var form_data = this.state.form_data;
        if (formEle_name == 'include-packaging') {
            form_data.detail.dependencies[formEle_name] = this.refs[formEle_name].getValue();
        }
        if (formEle_name == 'certificate') {
            form_data.detail.certificate = this.refs[formEle_name].getValue();
        } else {
            form_data[formEle_name] = this.refs[formEle_name].getValue();
        }
        this.setState({
            form_data: form_data
        });
    },

    render: function () {
        var config_info;
        var projects = this.state.projects;
        var projectsName = "";
        projects.map(function (project_info) {
            projectsName = projectsName + project_info.name + ";";
        });
        if (this.state.current_selected) {
            config_info = this.state.current_selected;
            var detail_edit = <div></div>;
            if (config_info.type == 'mk_back') {
                detail_edit = (
                    <div >
                        <SelectList title="是否包含第三方包"
                                    ref="include-packaging"
                                    onChange={function(){this.formChanged('include-packaging')}.bind(this)}
                                    defaultValue={this.state.form_data.detail.dependencies['include-packaging']}
                                    options={[{key:false,value:"false"},{key:true,value:"true"}]}
                        />
                    </div>
                )
            } else if(config_info.type == 'app_plugin'){
                detail_edit = (
                    <div>
                        <SelectList title="是否公开源码"
                                    ref="resource_publication"
                                    onChange={function(){this.formChanged('resource_publication')}.bind(this)}
                                    defaultValue={this.state.form_data.detail['resource_publication']}
                                    options={[{key:false,value:"false"},{key:true,value:"true"}]}
                        />
                    </div>
                );
            }else{
                detail_edit = (
                    <div>
                        <SelectList title="选择证书"
                                    ref="certificate"
                                    onChange={function(){this.formChanged('certificate')}.bind(this)}
                                    defaultValue={(this.state.form_data.detail && this.state.form_data.detail.certificate)?this.state.form_data.detail.certificate:"default"}
                                    options={this.state.certList}
                        />
                    </div>
                );
            }
            var icon;
            switch (config_info.type) {
                case "mk_back":
                    icon = <image src="/res/image/MK_h.png" style={{lineHeight:"40px",marginRight:"5px",marginTop:"-5px"}}/>;
                    break;
                case "app_android":
                    icon = <image src="/res/image/iphone_h.png" style={{lineHeight:"40px",marginRight:"5px",marginTop:"-5px"}}/>;
                    break;
                case "app_ios":
                    icon = <image src="/res/image/iphone_h.png" style={{lineHeight:"40px",marginRight:"5px",marginTop:"-5px"}}/>;
                    break;
                case "app_plugin":
                    icon = <i className="fa fa-plug" style={{fontSize:"23px"}} aria-hidden="true"/>
                    break;
            }
        }
        else {
            return (
                <div></div>
            );
        }
        return (
            <div style={{height:"100%"}}>
                <div id="cfg_detail_edit" style={{height:"100%"}}>
                    <div
                        style={{minWidth:"530px", maxWidth:"770px",width:"95%",overflowY:"auto",maxHeight:"calc(100% - 50px)"}}>
                        <Label defaultValue={config_info.type} title="产品类型"
                               icon={icon}/>
                        <Label defaultValue={this.state.current_project.title} title="所属项目"/>
                        <Input defaultValue={this.state.form_data.name} ref="name" title="配置名称"
                               onBlur={function(){this.formChanged('name')}.bind(this)}/>
                        <Input defaultValue={this.state.form_data.version} ref="version" title="版本信息"
                               onBlur={function(){this.formChanged('version')}.bind(this)}/>
                        <Selector defaultValue={projects} openSelectDialog={()=>{this.refs["projectList"].handleOpen()}}
                                  title="选择工程"/>
                        {detail_edit}
                    </div>
                    <div style={{minWidth:"530px", maxWidth:"770px",width:"97%",paddingTop:"10px"}}>
                        <div onClick={()=>{this.saveEdit()}}
                             style={{cursor:"pointer",width: "70px",height: "30px",fontSize:"13px",backgroundColor:"#303c40",padding:" 6px 16px",marginRight:"20px",float:"right"}}>
                            <span style={{letterSpacing: "2px",marginLeft:"5px",color:"white"}}>保存</span>
                        </div>
                    </div>
                </div>
                <ProjectsList ref="projectList"
                              getSelected={this.editProjects}
                              current_selected={this.state.current_selected}
                              current_project={this.state.current_project}
                />
            </div>
        )
    }
});
